package com.gzcc.core.security;

import com.gzcc.model.Admin;
import com.gzcc.repository.AdminRespository;
import com.gzcc.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 描述: security登录验证
 *
 * @Author: Mr.Zhong
 * @Date: 2018/6/13
 */
@Service
public class DbUserDetailsService implements UserDetailsService {
    @Autowired
    private AdminRespository adminRespository;

    /**
     * 描述: 输入的用户名验证
     *
     * @param name 用户名
     * @return UserDetails
     * @Author: Mr.Zhong
     * @Date: 2018/6/13
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        Admin admin = adminRespository.findByName(name);

        if (admin != null) {
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();

            authorities.add(new SimpleGrantedAuthority(admin.getRole().getName()));

            UserDetails userDetails = new User(admin.getName(), admin.getPassword(), authorities);
            return userDetails;
        } else {
            throw new UsernameNotFoundException("用户名不存在！");
        }


    }
}


